package com.sk.weichat.ui.groupchat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cjt2325.cameralibrary.util.LogUtil;
import com.sk.weichat.AppConstant;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.adapter.SelectContacts;
import com.sk.weichat.adapter.TabFragmentPagerAdapter;
import com.sk.weichat.bean.Area;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.MucRoom;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.broadcast.MucgroupUpdateUtil;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.EditBaseActivity;
import com.sk.weichat.ui.circle.PublishDynamicActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.ui.message.MucChatActivity;
import com.sk.weichat.ui.message.multi.AddContactsActivity;
import com.sk.weichat.ui.message.multi.EventGroupStatus;
import com.sk.weichat.util.AppUtils;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.DisplayUtil;
import com.sk.weichat.util.EventBusHelper;
import com.sk.weichat.util.JsonUtils;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.StringUtils;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.CircleImageView;
import com.sk.weichat.view.HorizontalListView;
import com.sk.weichat.view.ScaleTransitionPagerTitleView;
import com.sk.weichat.view.VerifyDialog;
import com.sk.weichat.xmpp.ListenerManager;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import okhttp3.Call;

public class TabSelectContactsActivity extends EditBaseActivity implements View.OnClickListener {
    private static final String[] CHANNELS = new String[]{"最近", "好友"};
    private List<String> mDataList = Arrays.asList(CHANNELS);
    private TabFragmentPagerAdapter mExamplePagerAdapter;
    private ViewPager mViewPager;
    private ArrayList<Fragment> mFragmentList;
    private TextView mTvTitle;
    private Button btn_title_right;
    private RelativeLayout added_layout;
    private int mTabPosition;
    private HorizontalListView mHorizontalListView;
    private HorListViewAdapter mHorAdapter;
    private List<String> mSelectPositions;
    private String mLoginUserId;

    private String mRoomId;
    private String mRoomJid;
    private String mRoomDes;
    private String mRoomName;
    private Set<String> mExistIds = new HashSet<>();

    // Todo 邀请成员 是否开启群主验证 2018.5.16
    private String mCreator;
    private VerifyDialog verifyDialog;

    // 是否是通过单人聊天快速创建的群组
    private boolean mQuicklyCreate;
    //     快速建群时聊天对象的id与备注名/昵称
    private String mQuicklyId;
    private String mQuicklyName;
    private int ReplyStatus;

    //是否是发送名片
    private boolean mSendCard;
    private boolean isRoom;//判断是群聊 还是私聊发送名片
    private List<String> mManagerList;

    //发送动态 Alt 好友

    private boolean isAltFriends;
    private List<String> mAltFriendList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_contacts_tab_layout);
        EventBusHelper.register(this);
        mTabPosition = getIntent().getIntExtra("tabPosition", 0);
        if (getIntent() != null) {
            //群聊邀请新成员
            mRoomId = getIntent().getStringExtra("roomId");
            mRoomJid = getIntent().getStringExtra("roomJid");
            mRoomDes = getIntent().getStringExtra("roomDes");
            mRoomName = getIntent().getStringExtra("roomName");
            String ids = getIntent().getStringExtra("exist_ids");
            String manager_ids = getIntent().getStringExtra("manager_ids");
            if (!TextUtils.isEmpty(manager_ids)) {
                mManagerList = StringUtils.stringToList(manager_ids);
            }

            mExistIds = JSON.parseObject(ids, new TypeReference<Set<String>>() {
            }.getType());
            mCreator = getIntent().getStringExtra("roomCreator");

            //私聊发起群聊
            mQuicklyCreate = getIntent().getBooleanExtra("QuicklyCreateGroup", false);
            mQuicklyId = getIntent().getStringExtra("ChatObjectId");
            mQuicklyName = getIntent().getStringExtra("ChatObjectName");
            ReplyStatus = getIntent().getIntExtra("ReplyStatus", -1);

            //群聊 私聊发送名片
            mSendCard = getIntent().getBooleanExtra("SendCard", false);
            isRoom = getIntent().getBooleanExtra("isRoom", false);

            isAltFriends = getIntent().getBooleanExtra("AltFriends", false);
            mAltFriendList = (List<String>) getIntent().getSerializableExtra("alt_userid");

        }
        mLoginUserId = coreManager.getSelf().getUserId();

        initActionBar();

        mViewPager = findViewById(R.id.view_pager);
        mFragmentList = new ArrayList<>();
        mFragmentList.add(RecentContactsFragment.getInstance());
        mFragmentList.add(SelectContactsFragment.getInstance());
        mExamplePagerAdapter = new TabFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList);
        mViewPager.setAdapter(mExamplePagerAdapter);
        mViewPager.setOffscreenPageLimit(2);
        mViewPager.setAdapter(mExamplePagerAdapter);

        initMagicIndicator();
        mViewPager.setCurrentItem(mTabPosition);  //初始化显示第一个页面

        mSelectPositions = new ArrayList<>();

        mHorAdapter = new HorListViewAdapter();
        added_layout = findViewById(R.id.added_layout);
        mHorizontalListView = findViewById(R.id.horizontal_list_view);
        mHorizontalListView.setAdapter(mHorAdapter);
        mHorizontalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

                if (mSelectPositions.get(position).equals(mLoginUserId)) {
                    ToastUtil.showToast(TabSelectContactsActivity.this, "快速建群，不能移除自己");
                    return;
                } else if (mSelectPositions.get(position).equals(mQuicklyId)) {
                    ToastUtil.showToast(TabSelectContactsActivity.this, " 快速建群，不能移除" + mQuicklyName);
                    return;
                }
                SelectContacts contacts = new SelectContacts();
                contacts.setUserId(mSelectPositions.get(position));
                contacts.setSelect(false);
                EventBus.getDefault().post(contacts);
            }
        });

        new Handler().postDelayed(new Runnable() {
            public void run() {
                //execute the task
                if (isAltFriends && mAltFriendList.size() > 0) {
                    for (int i = 0; i < mAltFriendList.size(); i++) {
                        mSelectPositions.add(mAltFriendList.get(i));
                        SelectContacts contacts = new SelectContacts();
                        contacts.setUserId(mAltFriendList.get(i));
                        contacts.setSelect(true);
                        EventBus.getDefault().post(contacts);
                    }
//            mSelectPositions.addAll(mAltFriendList);
//            mHorAdapter.notifyDataSetChanged();
                }
            }
        }, 200);


    }

    private void initActionBar() {
        getSupportActionBar().hide();
        mTvTitle = findViewById(R.id.tv_title_center);
        mTvTitle.setText("请选择好友");
        btn_title_right = findViewById(R.id.btn_title_right);
//        btn_title_right.setVisibility(View.VISIBLE);
        btn_title_right.setTextColor(getResources().getColor(R.color.deep_purple));
        btn_title_right.setBackgroundColor(getResources().getColor(R.color.white));
        btn_title_right.setText(getString(R.string.add_chat_ok_btn));
        findViewById(R.id.iv_title_left).setOnClickListener(this);
        btn_title_right.setOnClickListener(this);
        if (isAltFriends){
            btn_title_right.setVisibility(View.VISIBLE);
            btn_title_right.setText(getString(R.string.add_chat_ok_btn, "0"));
        }
    }

    private void initMagicIndicator() {
        MagicIndicator magicIndicator = findViewById(R.id.magic_indicator);
        magicIndicator.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {

                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setTextSize(20);
                simplePagerTitleView.setNormalColor(ContextCompat.getColor(TabSelectContactsActivity.this, R.color.text_color_main));
                simplePagerTitleView.setSelectedColor(ContextCompat.getColor(TabSelectContactsActivity.this, R.color.text_color_main));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setLineHeight(UIUtil.dip2px(context, 8));
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setColors(Color.parseColor("#40c4ff"));
                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, mViewPager);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    public Set<String> getExistIds() {
        return mExistIds;
    }

    public List<String> getSelectPositions() {
        return mSelectPositions;
    }

    public boolean isQuicklyCreate() {
        return mQuicklyCreate;
    }

    public String getQuicklyId() {
        return mQuicklyId;
    }

    public String getQuicklyName() {
        return mQuicklyName;
    }

    public List<String> getAltFriendList() {
        return mAltFriendList;
    }

    public boolean isAltFriends() {
        return isAltFriends;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.btn_title_right:
                if (mSendCard) {//发送名片
                    List<Friend> mFriendCardList = new ArrayList<>();
                    for (String key : mSelectPositions) {
                        Friend friend = FriendDao.getInstance().getFriend(mLoginUserId, key);
                        mFriendCardList.add(friend);
                    }

                    Intent intent = new Intent();
                    if (isRoom) {
                        intent.setClass(this, MucChatActivity.class);
                    } else {
                        intent.setClass(this, ChatActivity.class);
                    }
                    intent.putExtra("FriendCardList", (Serializable) mFriendCardList);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                } else if (isAltFriends) {
                    Intent intent = new Intent(TabSelectContactsActivity.this, PublishDynamicActivity.class);
                    List<Friend> mAltFriendList = new ArrayList<>();
                    for (String key : mSelectPositions) {
                        Friend friend = FriendDao.getInstance().getFriend(mLoginUserId, key);
                        mAltFriendList.add(friend);
                    }
                    intent.putExtra("AltFriendIdList", (Serializable) mSelectPositions);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    ClickBtnRight();
                }
//                ClickBtnRight();
                break;
        }
    }


    private void ClickBtnRight() {
        if (!coreManager.isLogin()) {
            ToastUtil.showToast(mContext, R.string.service_start_failed);
            return;
        }

        /*判断是否是群聊进来 邀请好友*/
        if (getExistIds() == null) {
            if (mQuicklyCreate) {//判断是否是私聊 发起群聊
                // 因为前面已经为mSelectPositions增加了一个虚线框,So
                if (mSelectPositions.size() < 3) {
                    ToastUtil.showToast(mContext, getString(R.string.tip_create_group_at_lease_one_friend));
                    return;
                }

                final List<Friend> friends = FriendDao.getInstance().getFriendsGroupChat(mLoginUserId);
                if (mQuicklyCreate) {
                    Friend friend = new Friend();
                    friend.setUserId(mLoginUserId);
                    friend.setNickName(coreManager.getSelf().getNickName());
                    friends.add(0, friend);
                }
//                Map<String, Integer> existMap = new HashMap<>();

//                List<BaseSortModel<Friend>> sortedList = SortHelper.toSortedModelList(friends, existMap, Friend::getShowName);
//                for (int i = 0; i < sortedList.size(); i++) {
//                    Friend friend = sortedList.get(i).getBean();
//                    if (friend.getUserId().equals(mLoginUserId) || friend.getUserId().equals(mQuicklyId)) {
//                        if (ReplyStatus!=0){
//                            SelectContacts contacts = new SelectContacts();
//                            contacts.setSelect(false);
//                            contacts.setUserId(friend.getUserId());
//                            EventBus.getDefault().post(contacts);
//                        }
//                    }
//                }
                String sc = "";
                if (ReplyStatus != 0) {//未回复过的状态
                    sc = coreManager.getSelf().getNickName() + "、" + mQuicklyName + "、";
                }
//                else {
//                     sc = coreManager.getSelf().getNickName() + "、" + mQuicklyName + "、";
//                }
                for (int i = 0; i < mSelectPositions.size(); i++) {
                    String name = "";
                    for (int i1 = 0; i1 < friends.size(); i1++) {
                        if (friends.get(i1).getUserId().equals(mSelectPositions.get(i))) {
                            name = !TextUtils.isEmpty(friends.get(i1).getRemarkName()) ? friends.get(i1).getRemarkName() : friends.get(i1).getNickName();
                        }
                    }
                    if (i == mSelectPositions.size() - 1) {
                        sc += name;
                    } else {
                        sc += name + "、";
                    }
                }
                createGroupChat(sc, "", 0, 1, 0, 1, 1);
            } else {
                if (mSelectPositions.size() < 2) {
                    ToastUtil.showToast(mContext, getString(R.string.tip_create_group_at_lease_one_friend));
                    return;
                }
                List<Friend> friends = FriendDao.getInstance().getFriendsGroupChat(mLoginUserId);
                String sc = coreManager.getSelf().getNickName() + "、";
                for (int i = 0; i < mSelectPositions.size(); i++) {
                    String name = "";
                    for (int i1 = 0; i1 < friends.size(); i1++) {
                        if (friends.get(i1).getUserId().equals(mSelectPositions.get(i))) {
                            name = !TextUtils.isEmpty(friends.get(i1).getRemarkName()) ? friends.get(i1).getRemarkName() : friends.get(i1).getNickName();
                        }
                    }
                    if (i == mSelectPositions.size() - 1) {
                        sc += name;
                    } else {
                        sc += name + "、";
                    }
                }
                createGroupChat(sc, "", 0, 1, 0, 1, 1);
            }

        } else {
            if (mSelectPositions.size() <= 0) {
                Toast.makeText(TabSelectContactsActivity.this, R.string.tip_select_at_lease_one_member, Toast.LENGTH_SHORT).show();
                return;
            }
            List<String> inviteIdList = new ArrayList<>();
            List<String> inviteNameList = new ArrayList<>();
            boolean isEmity = true;
            for (String fid : mSelectPositions) {
                Friend friend = FriendDao.getInstance().getFriend(mLoginUserId, fid);
                if (friend != null) {
                    inviteIdList.add(fid);
                    inviteNameList.add(friend.getNickName());
                    isEmity = false;
                }
            }

            if (isEmity) {
                return;
            }

            String userIds = AppUtils.listToString(inviteIdList);
            // 因为ios不要这样格式["10004541","10007042"]的字符串,，为了兼容他们，我们需要另外拼接一下
//                String ids = JSON.toJSONString(inviteIdList); // ["10004541","10007042"]
//                String names = JSON.toJSONString(inviteNameList); // ["haha","ccc"]
//                final String ios_ids = ids.substring(1, ids.length() - 1).replace("\"", ""); // 10004541,10007042
//                final String ios_name = names.substring(1, names.length() - 1).replace("\"", ""); // haha,ccc

            boolean isNeedOwnerAllowInviteFriend = PreferenceUtils.getBoolean(mContext, Constants.IS_NEED_OWNER_ALLOW_NORMAL_INVITE_FRIEND + mRoomJid, false);

            if (isNeedOwnerAllowInviteFriend) {// 群主开启了'群聊邀请确认'功能(需要群主确认进群)

                boolean isManger = false;
                for (String managerId : mManagerList) {
                    if (mLoginUserId.equals(managerId)) {// 我为群主或管理员，直接邀请
                        isManger = true;
                    }
                }
                if (isManger) {// 我为群主，直接邀请
                    inviteFriend(userIds);
                } else {
                    startActivityForResult(new Intent(this, InviteJoinRoomActivity.class).putExtra("roomId", mRoomId).putExtra("userIds", userIds), 100);

                     /*   verifyDialog = new VerifyDialog(TabSelectContactsActivity.this);
                        verifyDialog.setVerifyClickListener("", new VerifyDialog.VerifyClickListener() {
                            @Override
                            public void cancel() {

                            }
                            @Override
                            public void send(String str) {
                                // 给群主发送一条单聊消息

                                ChatMessage chatMessage = new ChatMessage();
                                String packetId=UUID.randomUUID().toString().replaceAll("-", "");
                                for(String managerId : mManagerList){
                                    ChatMessage message = new ChatMessage();
                                    message.setType(XmppMessage.TYPE_GROUP_VERIFY);
                                    message.setFromUserId(mLoginUserId);
                                    message.setToUserId(managerId);
                                    message.setFromUserName(coreManager.getSelf().getNickName());
                                    message.setIsEncrypt(0);

                                    String s = JsonUtils.initJsonContent(ios_ids, ios_name, mRoomJid, "0", str);
                                    message.setObjectId(s);
                                    message.setTimeSend(TimeUtils.sk_time_current_time());
                                    message.setPacketId(packetId);
                                    coreManager.sendChatMessage(managerId, message);
                                    chatMessage = message;
                                }
                                ChatMessage cm = chatMessage.clone(false);
                                cm.setType(XmppMessage.TYPE_TIP);
                                cm.setContent(getString(R.string.tip_send_reason_success));
                                if (ChatMessageDao.getInstance().saveNewSingleChatMessage(mLoginUserId, mRoomJid, cm)) {
                                    ListenerManager.getInstance().notifyNewMesssage(mLoginUserId, mRoomJid, cm, true);
                                }
                                finish();
                            }
                        });
                        verifyDialog.show();*/
                }
            } else {// 直接邀请
                inviteFriend(userIds);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(SelectContacts contacts) {

        if (contacts.isSelect()) {
            if (added_layout.getVisibility() == View.GONE) {
                added_layout.setVisibility(View.VISIBLE);
                btn_title_right.setVisibility(View.VISIBLE);
            }
//            for (int i = 0; i < mSelectPositions.size(); i++) {
//                if (!contacts.getUserId().equals(mSelectPositions.get(i))){
//                }
//            }

            if (!mSelectPositions.contains(contacts.getUserId())) {
                mSelectPositions.add(contacts.getUserId());
            }
            mHorAdapter.notifyDataSetChanged();
            btn_title_right.setText(getString(R.string.add_chat_ok_btn, mSelectPositions.size() + ""));
        } else {
            for (int i = 0; i < mSelectPositions.size(); i++) {
                String str = mSelectPositions.get(i);
                if (contacts.getUserId().equals(str)) {
                    mSelectPositions.remove(i);
                }
            }
            if (mSelectPositions.size() == 0) {
                added_layout.setVisibility(View.GONE);
                if (isAltFriends){
                    btn_title_right.setVisibility(View.VISIBLE);
                }else {
                    btn_title_right.setVisibility(View.GONE);
                }
            }
            mHorAdapter.notifyDataSetInvalidated();
            btn_title_right.setText(getString(R.string.add_chat_ok_btn, mSelectPositions.size() + ""));
        }
    }


    private class HorListViewAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mSelectPositions.size();
        }

        @Override
        public Object getItem(int position) {
            return mSelectPositions.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = new CircleImageView(mContext);
                int size = DisplayUtil.dip2px(mContext, 37);
                AbsListView.LayoutParams param = new AbsListView.LayoutParams(size, size);
                convertView.setLayoutParams(param);
            }
            ImageView imageView = (ImageView) convertView;
            String selectPosition = mSelectPositions.get(position);
            AvatarHelper.getInstance().displayAvatar(selectPosition, imageView, true);
            return convertView;
        }
    }

    private void createGroupChat(final String roomName, final String roomDesc, int isRead,
                                 int isLook, int isNeedVerify, int isShowMember, int isAllowSendCard) {
        final String roomJid = coreManager.createMucRoom(roomName);
        if (TextUtils.isEmpty(roomJid)) {
            ToastUtil.showToast(mContext, getString(R.string.create_room_failed));
            return;
        }
        MyApplication.mRoomKeyLastCreate = roomJid;
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("jid", roomJid);
        params.put("name", roomName);
        params.put("desc", roomDesc);
        params.put("countryId", String.valueOf(Area.getDefaultCountyId()));

        params.put("showRead", isRead + "");
        // 显示已读人数
        PreferenceUtils.putBoolean(mContext, Constants.IS_SHOW_READ + roomJid, isRead == 1);
        // 是否公开
        params.put("isLook", isLook + "");
        // 是否开启进群验证
        params.put("isNeedVerify", isNeedVerify + "");
        // 其他群管理
        params.put("showMember", isShowMember + "");
        params.put("allowSendCard", isAllowSendCard + "");

        params.put("allowInviteFriend", "1");
        params.put("allowUploadFile", "1");
        params.put("allowConference", "1");
        params.put("allowSpeakCourse", "1");

        PreferenceUtils.putBoolean(mContext, Constants.IS_SEND_CARD + roomJid, isAllowSendCard == 1);

        Area area = Area.getDefaultProvince();
        if (area != null) {
            params.put("provinceId", String.valueOf(area.getId()));    // 省份Id
        }
        area = Area.getDefaultCity();
        if (area != null) {
            params.put("cityId", String.valueOf(area.getId()));            // 城市Id
            area = Area.getDefaultDistrict(area.getId());
            if (area != null) {
                params.put("areaId", String.valueOf(area.getId()));        // 城市Id
            }
        }

        double latitude = MyApplication.getInstance().getBdLocationHelper().getLatitude();
        double longitude = MyApplication.getInstance().getBdLocationHelper().getLongitude();
        if (latitude != 0)
            params.put("latitude", String.valueOf(latitude));
        if (longitude != 0)
            params.put("longitude", String.valueOf(longitude));

        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().ROOM_ADD)
                .params(params)
                .build()
                .execute(new BaseCallback<MucRoom>(MucRoom.class) {

                    @Override
                    public void onResponse(ObjectResult<MucRoom> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
//                            if (mQuicklyCreate) {
//                                sendBroadcast(new Intent(com.sk.weichat.broadcast.OtherBroadcast.QC_FINISH)); // 快速建群成功，发送广播关闭之前的单聊界面
//                            }
                            createRoomSuccess(result.getData().getId(), roomJid, roomName, roomDesc);
                        } else {
                            MyApplication.mRoomKeyLastCreate = "compatible";// 还原回去
                            if (!TextUtils.isEmpty(result.getResultMsg())) {
                                ToastUtil.showToast(mContext, result.getResultMsg());
                            } else {
                                ToastUtil.showToast(mContext, R.string.tip_server_error);
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        MyApplication.mRoomKeyLastCreate = "compatible";// 还原回去
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    // 创建成功的时候将会调用此方法，将房间也存为好友
    private void createRoomSuccess(String roomId, String roomJid, String roomName, String
            roomDesc) {
        Friend friend = new Friend();
        friend.setOwnerId(mLoginUserId);
        friend.setUserId(roomJid);
        friend.setNickName(roomName);
        friend.setDescription(roomDesc);
        friend.setRoomFlag(1);
        friend.setRoomId(roomId);
        friend.setRoomCreateUserId(mLoginUserId);
        // timeSend作为取群聊离线消息的标志，所以要在这里设置一个初始值
        friend.setTimeSend(TimeUtils.sk_time_current_time());
        friend.setStatus(Friend.STATUS_FRIEND);
        FriendDao.getInstance().createOrUpdateFriend(friend);

        // 更新群组
        MucgroupUpdateUtil.broadcastUpdateUi(this);

        // 本地发送一条消息至该群 否则未邀请其他人时在消息列表不会显示
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setType(XmppMessage.TYPE_TIP);
        chatMessage.setFromUserId(mLoginUserId);
        chatMessage.setFromUserName(coreManager.getSelf().getNickName());
        chatMessage.setToUserId(roomJid);
        chatMessage.setContent(InternationalizationHelper.getString("NEW_FRIEND_CHAT"));
        chatMessage.setPacketId(coreManager.getSelf().getNickName());
        chatMessage.setTimeSend(TimeUtils.sk_time_current_time());
        if (ChatMessageDao.getInstance().saveNewSingleChatMessage(mLoginUserId, roomJid, chatMessage)) {
            // 更新聊天界面
            MsgBroadcast.broadcastMsgUiUpdate(TabSelectContactsActivity.this);
        }

        // 邀请好友
        String[] noticeFriendList = new String[mSelectPositions.size()];
        List<String> inviteUsers = new ArrayList<>();

        // 邀请好友
        for (int i = 0; i < mSelectPositions.size(); i++) {
            String userId = mSelectPositions.get(i);
            if (!userId.equals(mLoginUserId)) {
                inviteUsers.add(userId);
            }
        }
        if (mQuicklyCreate && ReplyStatus != 0) {
            inviteUsers.add(mQuicklyId);
        }
        inviteFriend(JSON.toJSONString(inviteUsers), roomId, roomJid, roomName, noticeFriendList);
    }

    /**
     * 直接邀请好友
     */
    private void inviteFriend(String userIds) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mRoomId);
        params.put("userIds", userIds);
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().ROOM_INVITE_AUTO_JINO)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (Result.checkSuccess(TabSelectContactsActivity.this, result)) {
                            ToastUtil.showToast(mContext, getString(R.string.invite_success));
                            EventBus.getDefault().post(new EventGroupStatus(111111, 0));//通知群列表刷新
                            setResult(RESULT_OK);
                            finish();
                        } else if (result.getResultCode() == 1040320) {
                            startActivityForResult(new Intent(TabSelectContactsActivity.this, InviteJoinRoomActivity.class).putExtra("roomId", mRoomId).putExtra("userIds", userIds), 100);
                        } else {
                            ToastUtil.showToast(TabSelectContactsActivity.this, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showNetError(mContext);
                    }
                });
    }

    /**
     * 邀请好友
     */
    private void inviteFriend(String text, String roomId, final String roomJid,
                              final String roomName, final String[] noticeFriendList) {
        if (mSelectPositions.size() <= 0) {
            // 进入群聊界面，结束当前的界面
            Intent intent = new Intent(TabSelectContactsActivity.this, MucChatActivity.class);
            intent.putExtra(AppConstant.EXTRA_USER_ID, roomJid);
            intent.putExtra(AppConstant.EXTRA_NICK_NAME, roomName);
            intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
            startActivity(intent);
            finish();
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", roomId);
        params.put("text", text);

        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().ROOM_MEMBER_UPDATE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        setResult(RESULT_OK);
                        EventBus.getDefault().post(new EventGroupStatus(111111, 0));//通知群列表刷新

                        // 进入群聊界面，结束当前的界面
                        Intent intent = new Intent(TabSelectContactsActivity.this, MucChatActivity.class);
                        intent.putExtra(AppConstant.EXTRA_USER_ID, roomJid);
                        intent.putExtra(AppConstant.EXTRA_NICK_NAME, roomName);
                        intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
                        intent.putExtra(Constants.GROUP_JOIN_NOTICE, noticeFriendList);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {
                finish();
            }
        }
    }
}
